import importlib
import requests
import inspect
import sys
import os

from plugins.plugin import Plugin
from src.history import History
from src.config import Config

class PlugMan:

    def __init__(self, history=History(), config=Config()) -> None:
        self.plugins    = list()
        self.extension  = '.py'
        self.history    = history
        self.config     = config

        self.plugins_dir = os.path.expanduser("~")+"/.config/rosemary/plugins"
        sys.path.append(self.plugins_dir)
         
    def inspect_obj(self, obj) -> bool:
        return inspect.isclass(obj) and issubclass(obj, Plugin) and obj != Plugin

    def add_plugin_from_module(self, pfile) -> None:
        for it in dir(pfile):
            obj = getattr(pfile, it)
            if self.inspect_obj(obj):
                plugin = obj(self.history, self.config)
                self.plugins.append(plugin)
                plugin.id = len(self.plugins)-1

    def load_user_plugin(self, fname) -> None:
        pfile = importlib.import_module(fname)
        self.add_plugin_from_module(pfile) 

    def load_plugins(self) -> None:
        print("#=====> Init plugins <=====#")
        for file in os.listdir(self.plugins_dir):
            if file.endswith(self.extension):
                file = file[:-3]

                print(f"    Init plugin: {file}...")
                
                pfile = importlib.import_module(file)
                self.add_plugin_from_module(pfile)
        print("#==========================#")

    def load_from_repo_by_name(self, name, pbfunc=None) -> str:
        if pbfunc != None: pbfunc(0,2,prefix=name,suffix='Complete',length=50)

        url = f'https://notabug.org/loliconshik3/rosepg/raw/master/plugins/{name}.py'
        resp = requests.get(url)

        if resp.status_code != 200: return f"Error: Plugin {name} not found!"

        if pbfunc != None: pbfunc(1,2,prefix=name,suffix='Complete',length=50)

        with open(f"{self.plugins_dir}/{name}.py", 'w') as file:
            file.write(resp.text)

        if pbfunc != None: pbfunc(2,2,prefix=name,suffix='Complete',length=50)

        self.load_user_plugin(name)

        return f"OK: {name} plugin installation complete!" 

    def remove_plugin(self, name, pbfunc=None) -> str:
        if pbfunc != None: pbfunc(0,1,prefix=name,suffix='Complete',length=50)

        path = f"{self.plugins_dir}/{name}.py"
        if not os.path.exists(path): return f"Error: {name} plugin not found!"
        os.remove(path)

        if pbfunc != None: pbfunc(1,1,prefix=name,suffix='Complete',length=50)

        return f"OK: {name} plugin removed!"

    def update_all_user_plugins(self, pbfunc=None) -> None:
        for file in os.listdir(self.plugins_dir):
            if file.endswith(self.extension):
                filename = file[:-3]
                self.load_from_repo_by_name(filename, pbfunc=pbfunc)  

    def install_default_plugins(self) -> None:
        self.load_from_repo_by_name("iv_search")
        self.load_from_repo_by_name("iv_lvideos")
        self.load_from_repo_by_name("iv_subscribes")
        self.load_from_repo_by_name("iv_popular")
        self.load_from_repo_by_name("iv_trending")
    
    def get_repo_plugins(self) -> str:
        url = f'https://notabug.org/loliconshik3/rosen-plugins/raw/master/README.md'
        resp = requests.get(url)
        if resp.status_code != 200: return "Error: Page unavailable!"
        return resp.text        

    def print_plugins(self) -> None:
        for plugin in self.plugins:
            print(plugin.name)

    def get_plugin_by_name(self, name) -> (Plugin | None):
        for plugin in self.plugins:
            if plugin.name == name: return plugin

    def get_plugin_by_id(self, id) -> (Plugin | None):
        for plugin in self.plugins: 
            if plugin.id == id: return plugin

if __name__ == "__main__":
    pm = PlugMan()
    pm.print_plugins()




